<template>
  <div class="review-time-settings">
    <h2>评审时间设置</h2>
    <p class="subtitle">设置各专业组的评审时间段及状态</p>

    <!-- 专业组设置卡片容器 -->
    <div class="setting-cards">
      <!-- 油气勘探 -->
      <div class="setting-card">
        <div class="card-header">
          <div class="group-info">
            <el-tag type="primary" size="medium">油气勘探</el-tag>
            <span class="status-indicator" :class="statusClass('exploration')">
              {{ statusText('exploration') }}
            </span>
          </div>
          <el-switch
              v-model="groups.exploration.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange('exploration')"
          >
          </el-switch>
        </div>

        <div class="card-body">
          <el-form>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="评审开始时间">
                  <el-date-picker
                      v-model="groups.exploration.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.exploration.active"
                      @change="validateTime('exploration')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评审结束时间">
                  <el-date-picker
                      v-model="groups.exploration.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.exploration.active"
                      @change="validateTime('exploration')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="time-validation" v-if="groups.exploration.validationError">
            <i class="el-icon-error-circle"></i>
            <span>{{ groups.exploration.validationError }}</span>
          </div>
        </div>
      </div>

      <!-- 油气藏工程 -->
      <div class="setting-card">
        <div class="card-header">
          <div class="group-info">
            <el-tag type="success" size="medium">油气藏工程</el-tag>
            <span class="status-indicator" :class="statusClass('reservoir')">
              {{ statusText('reservoir') }}
            </span>
          </div>
          <el-switch
              v-model="groups.reservoir.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange('reservoir')"
          >
          </el-switch>
        </div>

        <div class="card-body">
          <el-form>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="评审开始时间">
                  <el-date-picker
                      v-model="groups.reservoir.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.reservoir.active"
                      @change="validateTime('reservoir')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评审结束时间">
                  <el-date-picker
                      v-model="groups.reservoir.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.reservoir.active"
                      @change="validateTime('reservoir')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="time-validation" v-if="groups.reservoir.validationError">
            <i class="el-icon-error-circle"></i>
            <span>{{ groups.reservoir.validationError }}</span>
          </div>
        </div>
      </div>

      <!-- 钻采与地面工程 -->
      <div class="setting-card">
        <div class="card-header">
          <div class="group-info">
            <el-tag type="warning" size="medium">钻采与地面工程</el-tag>
            <span class="status-indicator" :class="statusClass('drilling')">
              {{ statusText('drilling') }}
            </span>
          </div>
          <el-switch
              v-model="groups.drilling.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange('drilling')"
          >
          </el-switch>
        </div>

        <div class="card-body">
          <el-form>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="评审开始时间">
                  <el-date-picker
                      v-model="groups.drilling.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.drilling.active"
                      @change="validateTime('drilling')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评审结束时间">
                  <el-date-picker
                      v-model="groups.drilling.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.drilling.active"
                      @change="validateTime('drilling')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="time-validation" v-if="groups.drilling.validationError">
            <i class="el-icon-error-circle"></i>
            <span>{{ groups.drilling.validationError }}</span>
          </div>
        </div>
      </div>

      <!-- 信息工程 -->
      <div class="setting-card">
        <div class="card-header">
          <div class="group-info">
            <el-tag type="info" size="medium">信息工程</el-tag>
            <span class="status-indicator" :class="statusClass('information')">
              {{ statusText('information') }}
            </span>
          </div>
          <el-switch
              v-model="groups.information.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange('information')"
          >
          </el-switch>
        </div>

        <div class="card-body">
          <el-form>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="评审开始时间">
                  <el-date-picker
                      v-model="groups.information.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.information.active"
                      @change="validateTime('information')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评审结束时间">
                  <el-date-picker
                      v-model="groups.information.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :disabled="!groups.information.active"
                      @change="validateTime('information')"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="time-validation" v-if="groups.information.validationError">
            <i class="el-icon-error-circle"></i>
            <span>{{ groups.information.validationError }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          type="primary"
          size="medium"
          @click="saveAllSettings"
          :loading="saveLoading"
      >
        <i class="el-icon-check"></i> 保存所有设置
      </el-button>
      <el-button
          size="medium"
          @click="resetSettings"
          style="margin-left: 15px;"
      >
        <i class="el-icon-refresh"></i> 重置
      </el-button>
    </div>
  </div>
</template>

<script>
// 导入API
import {
  getAllSchedules,
  batchSaveOrUpdate,
  resetAllSchedules
} from '@/api/reviewSchedule'

export default {
  data() {
    return {
      saveLoading: false,
      // 四个专业组的设置
      groups: {
        exploration: {  // 油气勘探
          id: null, // 新增：用于存储后端返回的ID
          active: false,
          startTime: '',
          endTime: '',
          validationError: ''
        },
        reservoir: {  // 油气藏工程
          id: null,
          active: false,
          startTime: '',
          endTime: '',
          validationError: ''
        },
        drilling: {  // 钻采与地面工程
          id: null,
          active: false,
          startTime: '',
          endTime: '',
          validationError: ''
        },
        information: {  // 信息工程
          id: null,
          active: false,
          startTime: '',
          endTime: '',
          validationError: ''
        }
      },
      // 专业组中文名称映射表
      specialtyMap: {
        exploration: '油气勘探',
        reservoir: '油气藏工程',
        drilling: '钻采与地面工程',
        information: '信息工程'
      }
    };
  },
  created() {
    // 页面初始化时加载数据
    this.loadAllSchedules();
  },
  methods: {
    // 加载所有评审时间设置
    async loadAllSchedules() {
      try {
        const response = await getAllSchedules();
        console.log(response)
        if (response.code === '200' && response.data) {
          this.parseSchedules(response.data);
        } else {
          this.$message.warning('加载评审时间设置失败');
        }
      } catch (error) {
        console.error('加载评审时间设置出错:', error);
        this.$message.error('加载失败，请刷新页面重试');
      }
    },

    // 解析后端返回的评审时间数据
    parseSchedules(schedules) {
      // 先清空现有数据
      Object.keys(this.groups).forEach(key => {
        this.groups[key] = {
          ...this.groups[key],
          active: false,
          startTime: '',
          endTime: '',
          id: null
        };
      });

      // 填充后端数据
      schedules.forEach(schedule => {
        // 找到对应的专业组键名
        const groupKey = Object.keys(this.specialtyMap).find(
            key => this.specialtyMap[key] === schedule.specialty
        );

        if (groupKey) {
          this.groups[groupKey] = {
            id: schedule.id,
            active: schedule.status === 1, // 1-开启，2-关闭
            startTime: schedule.startTime || '',
            endTime: schedule.endTime || '',
            validationError: ''
          };
        }
      });
    },

    // 获取状态显示文本
    statusText(groupKey) {
      const group = this.groups[groupKey];
      if (!group.active) return '已关闭';

      // 如果未设置完整时间
      if (!group.startTime || !group.endTime) return '待设置时间';

      // 检查时间状态
      const now = new Date();
      const start = new Date(group.startTime);
      const end = new Date(group.endTime);

      if (now < start) return '未开始';
      if (now >= start && now <= end) return '评审中';
      if (now > end) return '已结束';

      return '已开启';
    },

    // 获取状态样式类
    statusClass(groupKey) {
      const group = this.groups[groupKey];
      if (!group.active) return 'status-disabled';

      if (!group.startTime || !group.endTime) return 'status-pending';

      const now = new Date();
      const start = new Date(group.startTime);
      const end = new Date(group.endTime);

      if (now < start) return 'status-upcoming';
      if (now >= start && now <= end) return 'status-active';
      if (now > end) return 'status-completed';

      return 'status-enabled';
    },

    // 处理状态切换
    handleStatusChange(groupKey) {
      const group = this.groups[groupKey];
      // 如果关闭状态，清空验证错误
      if (!group.active) {
        group.validationError = '';
      } else {
        // 如果开启状态，检查是否有时间需要验证
        this.validateTime(groupKey);
      }
    },

    // 验证时间有效性
    validateTime(groupKey) {
      const group = this.groups[groupKey];
      group.validationError = '';

      // 如果未启用，不需要验证
      if (!group.active) return true;

      // 检查是否填写完整
      if (!group.startTime || !group.endTime) {
        group.validationError = '请设置完整的评审时间段';
        return false;
      }

      // 检查时间逻辑
      const start = new Date(group.startTime);
      const end = new Date(group.endTime);

      if (start >= end) {
        group.validationError = '开始时间不能晚于结束时间';
        return false;
      }

      return true;
    },

    // 保存所有设置
    async saveAllSettings() {
      // 先验证所有启用的专业组
      let isValid = true;
      Object.keys(this.groups).forEach(key => {
        if (this.groups[key].active) {
          if (!this.validateTime(key)) {
            isValid = false;
          }
        }
      });

      if (!isValid) {
        this.$message.warning('请修正时间设置中的错误');
        return;
      }

      // 准备提交给后端的数据
      const submitData = Object.keys(this.groups).map(key => {
        const group = this.groups[key];
        return {
          id: group.id, // 用于更新已有记录
          specialty: this.specialtyMap[key], // 专业组中文名称
          startTime: group.active ? group.startTime : null,
          endTime: group.active ? group.endTime : null,
          status: group.active ? 1 : 2 // 1-开启，2-关闭
        };
      });
      this.saveLoading = true;
      try {
        const response = await batchSaveOrUpdate(submitData);
        if (response.code === '200') {
          this.$message.success('所有评审时间设置已保存');
          // 重新加载数据，确保显示最新状态
          await this.loadAllSchedules();
        } else {
          this.$message.error('保存失败：' + (response.msg || '未知错误'));
        }
      } catch (error) {
        console.error('保存评审时间设置出错:', error);
        this.$message.error('保存失败，请重试');
      } finally {
        this.saveLoading = false;
      }
    },

    // 重置设置
    async resetSettings() {
      this.$confirm('确定要重置所有设置吗？当前设置将被清空', '确认重置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await resetAllSchedules();
          if (response.success) {
            this.$message.success('设置已重置');
            // 重新加载数据
            this.loadAllSchedules();
          } else {
            this.$message.error('重置失败：' + (response.msg || '未知错误'));
          }
        } catch (error) {
          console.error('重置评审时间设置出错:', error);
          this.$message.error('重置失败，请重试');
        }
      }).catch(() => {
        // 取消重置，不做处理
      });
    }
  }
};
</script>

<style scoped>
.review-time-settings {
  padding: 20px;
  background-color: #f5f7fa;
  margin: 0 auto;
}

h2 {
  margin: 0 0 10px 0;
  color: #1f2329;
  font-size: 1.5rem;
}

.subtitle {
  color: #86909c;
  margin: 0 0 25px 0;
  font-size: 0.95rem;
}

.setting-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.setting-card {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.setting-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.group-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-indicator {
  font-size: 0.85rem;
  padding: 2px 8px;
  border-radius: 12px;
}

.status-disabled {
  background-color: #fef0f0;
  color: #f5222d;
}

.status-pending {
  background-color: #fff7e6;
  color: #faad14;
}

.status-upcoming {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-completed {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.status-enabled {
  background-color: #f0f9ff;
  color: #0050b3;
}

.card-body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  font-weight: 500;
  color: #4e5969;
}

.time-validation {
  color: #f5222d;
  font-size: 0.85rem;
  padding: 5px 0;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: -10px;
  width: 100%;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  padding: 10px 0;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .setting-cards {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .action-buttons .el-button {
    width: 100%;
    margin-left: 0 !important;
  }
}
</style>
